{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# AI搜索与MCP技术实战培训课程课件\n",
    "\n",
    "## 课程目标\n",
    "- 理解AI搜索技术（全文检索、向量检索）与MCP协议的原理与应用\n",
    "- 掌握AI搜索API调用与集成方法\n",
    "- 能独立开发MCP Server与Client，完成实际业务场景（天气、订单）工具开发\n",
    "- 掌握AI搜索与MCP服务的集成方法，实现智能问答与工具调用\n",
    "- 熟悉系统的整体架构设计与开发流程\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 1. AI搜索技术概述\n",
    "- AI搜索的基本概念与发展趋势\n",
    "- 全文检索（倒排索引、关键词匹配）与向量检索（语义检索、embedding、ANN）对比\n",
    "- 典型应用场景：智能问答、知识库检索、信息聚合\n",
    "- 主流开源/商用方案简介（如Elasticsearch、Milvus、Pinecone、BochaAI/Brave API等）\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 全文检索与向量检索示意代码\n",
    "\n",
    "全文检索（如Elasticsearch）示例：\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from elasticsearch import Elasticsearch\n",
    "es = Elasticsearch(['http://localhost:9200'])\n",
    "query = {\n",
    "    'query': {\n",
    "        'match': {\n",
    "            'content': 'AI搜索'\n",
    "        }\n",
    "    }\n",
    "}\n",
    "results = es.search(index='docs', body=query)\n",
    "print(results)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "向量检索（如Milvus）示例：\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from pymilvus import Collection\n",
    "collection = Collection('vector_docs')\n",
    "query_vector = [0.1, 0.2, 0.3, ...]  # 假设已生成embedding\n",
    "results = collection.search([query_vector], 'embedding', param={\"metric_type\": \"L2\"}, limit=5)\n",
    "print(results)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 2. 技术架构与系统设计\n",
    "- 系统整体架构图与分层说明\n",
    "- FastAPI主服务、MCP Server、MCP Client、数据库、静态资源的关系\n",
    "- 数据流与调用链路\n",
    "- 全文检索与向量检索在系统中的集成方式\n",
    "\n",
    "<img src=\"search-arch.png\" width=\"1000\">\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 3. AI搜索API调用\n",
    "- 搜索API的作用与典型场景\n",
    "- 以BochaAI API为例，讲解API Key配置、请求参数、结果解析\n",
    "- 搜索API调用的Python实现与异常处理\n",
    "- 搜索结果与AI大模型结合的方式\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import requests\n",
    "def bochaai_search(query, api_key):\n",
    "    url = 'https://api.bochaai.com/v1/web-search'\n",
    "    headers = {\n",
    "        'Content-Type': 'application/json',\n",
    "        'Authorization': f'Bearer {api_key}'\n",
    "    }\n",
    "    payload = {\n",
    "        'query': query,\n",
    "        'freshness': 'noLimit',\n",
    "        'summary': True,\n",
    "        'count': 10\n",
    "    }\n",
    "    resp = requests.post(url, headers=headers, json=payload)\n",
    "    return resp.json()\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 4. MCP原理与协议机制\n",
    "- MCP协议简介：目标、优势、核心概念（Tools/Resources/Prompts）\n",
    "- MCP Server与Client的通信机制（Stdio/SSE）\n",
    "- MCP工具注册、发现与调用流程\n",
    "- MCP与传统API的区别与优势\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# MCP工具注册示例\n",
    "from fastmcp import FastMCP\n",
    "mcp = FastMCP('demo-mcp')\n",
    "@mcp.tool()\n",
    "def add(a: int, b: int) -> int:\n",
    "    return a + b\n",
    "app = mcp.sse_app()\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 5. MCP Server实战开发\n",
    "- FastMCP框架介绍与依赖安装\n",
    "- MCP服务的功能设计与接口定义\n",
    "- 工具（Tool）与资源（Resource）注册\n",
    "- SSE服务启动与调试\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 天气MCP服务核心代码示例\n",
    "from fastmcp import FastMCP\n",
    "import requests\n",
    "mcp = FastMCP('weatherMcp', dependencies=['requests'], host='127.0.0.1', port=9001)\n",
    "@mcp.tool()\n",
    "def get_current_weather(province: str, city: str) -> str:\n",
    "    # 省略城市编码映射与API调用细节\n",
    "    return '天气数据'\n",
    "app = mcp.sse_app()\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 6. MCP Client开发与集成\n",
    "- FastMCP SSE/STDIO两种模式\n",
    "- FastMCP Client开发\n",
    "- 工具发现、参数传递、结果获取\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# MCP Client调用示例\n",
    "from fastmcp import Client\n",
    "from fastmcp.client.transports import SSETransport\n",
    "import asyncio\n",
    "async def call_weather():\n",
    "    async with Client(SSETransport('http://127.0.0.1:9001')) as client:\n",
    "        result = await client.call_tool('get_current_weather', {'province': '北京', 'city': '北京'})\n",
    "        print(result)\n",
    "# asyncio.run(call_weather())\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 7. 天气预报查询MCP服务开发\n",
    "- 天气MCP服务的功能设计与接口定义\n",
    "- 城市编码映射与第三方天气API集成\n",
    "- 工具（Tool）注册与参数校验\n",
    "- 服务启动与调试方法\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 见第5节天气MCP服务核心代码\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 8. 订单表查询MCP服务开发\n",
    "- 订单表结构与数据准备\n",
    "- 典型查询工具开发\n",
    "- SQL参数化查询与安全性\n",
    "- MCP工具的多样化输入输出设计\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 订单MCP服务核心代码示例\n",
    "from fastmcp import FastMCP\n",
    "import sqlite3\n",
    "conn = sqlite3.connect('chat_history.db')\n",
    "cursor = conn.cursor()\n",
    "mcp = FastMCP('order service mcp')\n",
    "@mcp.tool(description='获取指定月份的销售总额')\n",
    "def get_monthly_sales_total(month: int) -> str:\n",
    "    # 省略SQL细节\n",
    "    return '销售总额'\n",
    "app = mcp.sse_app()\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 9. MCP服务集成和应用\n",
    "- MCP管理相关API接口设计和开发\n",
    "- 智能体如何根据用户意图自动选择工具\n",
    "- 典型业务场景演示：如最受欢迎产品、销售员排行榜\n",
    "- 日志、异常与结果追踪\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# FastAPI集成MCP Client核心片段\n",
    "from fastapi import FastAPI\n",
    "from mcp_api import router as mcp_router\n",
    "app = FastAPI()\n",
    "app.include_router(mcp_router)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 10. 总结与展望\n",
    "- 课程知识点回顾\n",
    "- AI搜索与MCP技术的未来发展趋势\n",
    "- 项目实战与落地建议\n"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python",
   "version": "3.8"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
